<template>
	<el-form ref="ruleFormRef" :model="state.ruleForm" size="large" :rules="state.rules" class="login-content-form">
		<el-form-item class="login-animation1">
			<el-input ref="accountRef" text :placeholder="$t('message.account.accountPlaceholder1')" v-model="state.ruleForm.account" clearable autocomplete="off" @keyup.enter.native="handleSignIn">
				<template #prefix>
					<el-icon class="el-input__icon"><ele-User /></el-icon>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2">
			<el-input ref="passwordRef"
				:type="state.isShowPassword ? 'text' : 'password'"
				:placeholder="$t('message.account.accountPlaceholder2')"
				v-model="state.ruleForm.password"
				autocomplete="off"
				@keyup.enter.native="handleSignIn"
			>
				<template #prefix>
					<el-icon class="el-input__icon"><ele-Unlock /></el-icon>
				</template>
				<template #suffix>
					<i
						class="iconfont el-input__icon login-content-password"
						:class="state.isShowPassword ? 'icon-yincangmima' : 'icon-xianshimima'"
						@click="state.isShowPassword = !state.isShowPassword"
					>
					</i>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation3">
			<el-col :span="15">
				<el-input
					ref="codeRef"
					text
					maxlength="4"
					:placeholder="$t('message.account.accountPlaceholder3')"
					v-model="state.ruleForm.code"
					clearable
					autocomplete="off"
					@keyup.enter.native="handleSignIn"
				>
					<template #prefix>
						<el-icon class="el-input__icon"><ele-Position /></el-icon>
					</template>
				</el-input>
			</el-col>
			<el-col :span="1"></el-col>
			<el-col :span="8">
				<!-- <el-button class="login-content-code" v-waves>1234</el-button> -->
				<div class="login-content-code">
					<img class="login-content-code-img" @click="getCaptcha" width="130px" height="38px" :src="state.captchaImage" style="cursor: pointer" />
				</div>
			</el-col>
		</el-form-item>
		<el-form-item class="login-animation4">
			<el-button type="primary" class="login-content-submit" round v-waves @click="handleSignIn" :loading="state.loading.signIn">
				<span>{{ $t('message.account.accountBtnText') }}</span>
			</el-button>
		</el-form-item>
	</el-form>
	<div class="dialog-header">
		<el-dialog v-model="state.rotateVerifyVisible" :show-close="false">
			<DragVerifyImgRotate
				ref="dragRef"
				:imgsrc="state.rotateVerifyImg"
				v-model:isPassing="state.isPassRotate"
				text="请按住滑块拖动"
				successText="验证通过"
				handlerIcon="fa fa-angle-double-right"
				successIcon="fa fa-hand-peace-o"
				@passcallback="passRotateVerify"
			/>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="loginAccount">
import { onMounted, ref, reactive, computed, defineAsyncComponent } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import Cookies from 'js-cookie';
//import { storeToRefs } from 'pinia';
//import { useThemeConfig } from '/@/stores/themeConfig';
// import { initFrontEndControlRoutes } from '/@/router/frontEnd';
// import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Session, Local , accessTokenKey } from '/@/utils/storage';
import { formatAxis } from '/@/utils/formatTime';
import { NextLoading } from '/@/utils/loading';
import { useAuthApi } from '/@/api/auth';
import { useLoginApi } from '/@/api/login';
import { initControlRoutes } from '/@/router/controlroutes';
import { sm2 } from 'sm-crypto-v2';

// 旋转图片滑块组件
import verifyImg from '/@/assets/logo-mini.svg';
const DragVerifyImgRotate = defineAsyncComponent(() => import('/@/components/dragVerify/dragVerifyImgRotate.vue'));
// 定义变量内容
const { t } = useI18n();
//const storesThemeConfig = useThemeConfig();
//const { themeConfig } = storeToRefs(storesThemeConfig);
const route = useRoute();
const router = useRouter();

const ruleFormRef = ref();
const accountRef = ref<InputInstance>();
const passwordRef = ref<InputInstance>();
const codeRef = ref<InputInstance>();

const state = reactive({
	isShowPassword: false,
	ruleForm: {
		account: 'superAdmin',
		password: '123456',
		code: '',
		codeId:0,
	},
	rules:{
		account: [{ required: true, message: "$t('message.account.accountPlaceholder1')", trigger: 'blur' }],
		password: [{ required: true, message: "$t('message.account.accountPlaceholder2')", trigger: 'blur' }],
		code: [{ required: true, message: "$t('message.account.accountPlaceholder3')", trigger: 'blur' }],
	},
	loading: {
		signIn: false,
	},
	captchaImage: '',
	rotateVerifyVisible: false,
	rotateVerifyImg: verifyImg,
	secondVerEnabled: false,
	captchaEnabled: false,
	isPassRotate: false,
});
onMounted(async () => {
	// 若URL带有Token参数（第三方登录）
	var accessToken = route.query.token;
	if (accessToken != null && accessToken != undefined) {
		await saveTokenAndInitRoutes(accessToken);
	}
	useAuthApi().loginConfig().then(async (res: AjaxResult) => {
		state.secondVerEnabled = res.data.secondVerEnabled ?? true;
		state.captchaEnabled = res.data.captchaEnabled ?? true;
		getCaptcha();
	});

	// // 获取登录配置
	// var res1 = await getAPI(SysAuthApi).apiSysAuthLoginConfigGet();
	// state.secondVerEnabled = res1.data.result.secondVerEnabled ?? true;
	// state.captchaEnabled = res1.data.result.captchaEnabled ?? true;

});
// 获取验证码
const getCaptcha = async () => {
	if (!state.captchaEnabled) return;

	state.ruleForm.code = '';
	useAuthApi().authCaptcha(state.ruleForm).then(async (res: AjaxResult) => {
		state.captchaImage = 'data:text/html;base64,' + res.data?.img;
		state.ruleForm.codeId = res.data?.id;
	});
console.log('img:'+state.captchaImage);
console.log('id:'+state.ruleForm.codeId);
	// var res = await getAPI(SysAuthApi).apiSysAuthCaptchaGet();
	// state.captchaImage = 'data:text/html;base64,' + res.data.result?.img;
	// state.ruleForm.codeId = res.data.result?.id;
};



// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});
// 登录
const onSignIn = async () => {
	ruleFormRef.value.validate(async (valid: boolean) => {
		if(!valid) return false;
		try{
			state.loading.signIn = true;
			// SM2加密密码
			// const keys = SM2.generateKeyPair();
			const publicKey = `0484C7466D950E120E5ECE5DD85D0C90EAA85081A3A2BD7C57AE6DC822EFCCBD66620C67B0103FC8DD280E36C3B282977B722AAEC3C56518EDCEBAFB72C5A05312`;
			const _password = sm2.doEncrypt(state.ruleForm.password, publicKey, 1);
			//useLoginApi().signIn({state.ruleForm, password: _password}).then(async (res: AjaxResult) => {
			useLoginApi().signIn({"account":state.ruleForm.account,"password":_password,"code":state.ruleForm.code,"codeId":state.ruleForm.codeId}).then(async (res: AjaxResult) => {
				if(!res.success){
					ElMessage.warning('登录失败：' + res.message);
					getCaptcha(); // 重新获取验证码
					return;
				}
				if (res.data?.accessToken == undefined) {
					getCaptcha(); // 重新获取验证码
					ElMessage.error('登录失败，请检查账号！');
					return;
				}
				await saveTokenAndInitRoutes(res.data?.accessToken);

				// const isNoPower = await initControlRoutes();
				// signInSuccess(isNoPower);

				//const _result=res as AjasResult;
				console.log(JSON.stringify(res));
				// if (res.success == true) {
				// 	Session.set('token', res.data.accessToken);
				// 	Cookies.set('userName', state.ruleForm.account);
				// 	// eslint-disable-next-line no-console
				// 	console.log('登录成功：' + JSON.stringify(res));
				// 	// console.log('登录时间' + currentTime.value);
				// 	const isNoPower = await initControlRoutes();
				// 	signInSuccess(isNoPower);
				// }
				// else {
				// 	ElMessage.warning('登录失败：' + res.message);
				// 	state.loading.signIn = false;
				// }
			});
		}finally {
			state.loading.signIn = false;
		}
	});
}
// const onSignIn = async () => {
// 	state.loading.signIn = true;
// 	// 存储 token 到浏览器缓存
// 	Session.set('token', Math.random().toString(36).substr(0));
// 	// 模拟数据，对接接口时，记得删除多余代码及对应依赖的引入。用于 `/src/stores/userInfo.ts` 中不同用户登录判断（模拟数据）
// 	Cookies.set('userName', state.ruleForm.userName);
// 	if (!themeConfig.value.isRequestRoutes) {
// 		// 前端控制路由，2、请注意执行顺序
// 		const isNoPower = await initFrontEndControlRoutes();
// 		signInSuccess(isNoPower);
// 	} else {
// 		// 模拟后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
// 		// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
// 		const isNoPower = await initBackEndControlRoutes();
// 		// 执行完 initBackEndControlRoutes，再执行 signInSuccess
// 		signInSuccess(isNoPower);
// 	}
// };

// 保持Token并初始化路由
const saveTokenAndInitRoutes = async (accessToken: string | any) => {
	// 缓存token
	//Cookies.set('userName', state.ruleForm.account);
	//Cookies.set(accessTokenKey, accessToken);
	Local.set(accessTokenKey, accessToken);
	// Local.set(refreshAccessTokenKey, refreshAccessToken);
	Session.set('token', accessToken);

	// 添加完动态路由再进行router跳转，否则可能报错 No match found for location with path "/"
	//const isNoPower = await initBackEndControlRoutes();
	const isNoPower = await initControlRoutes();
	signInSuccess(isNoPower); // 再执行 signInSuccess
};

// 登录成功后的跳转
const signInSuccess = (isNoPower: boolean | undefined) => {
	if (isNoPower) {
		ElMessage.warning('抱歉，您没有登录权限');
		Session.clear();
	} else {
		// 初始化登录成功时间问候语
		let currentTimeInfo = currentTime.value;
		// 登录成功，跳到转首页
		// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
		if (route.query?.redirect) {
			router.push({
				path: <string>route.query?.redirect,
				query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
			});
		} else {
			router.push('/');
		}
		// 登录成功提示
		const signInText = t('message.signInText');
		ElMessage.success(`${currentTimeInfo}，${signInText}`);
		// 添加 loading，防止第一次进入界面时出现短暂空白
		NextLoading.start();
	}
	state.loading.signIn = false;
};

// 打开旋转验证
const openRotateVerify = () => {
	state.rotateVerifyVisible = true;
	state.isPassRotate = false;
	dragRef.value?.reset();
};
// 通过旋转验证
const passRotateVerify = () => {
	state.rotateVerifyVisible = false;
	state.isPassRotate = true;
	onSignIn();
};

// 登录处理
const handleSignIn = () => {
	if (!state.ruleForm.account) {
		accountRef.value?.focus();
		ElMessage.warning('账号不能为空');
	} else if (!state.ruleForm.password) {
		passwordRef.value?.focus();
		ElMessage.warning('密码不能为空');
	} else if (state.captchaEnabled && !state.ruleForm.code) {
		codeRef.value?.focus();
		ElMessage.warning('验证码不能为空');
	} else {
		state.secondVerEnabled ? openRotateVerify() : onSignIn();
	}
};
</script>

<style scoped lang="scss">
.dialog-header {
	:deep(.el-dialog) {
		.el-dialog__header {
			display: none;
		}

		.el-dialog__wrapper {
			position: absolute !important;
		}

		.v-modal {
			position: absolute !important;
		}

		width: unset !important;
	}
}

.login-content-form {
	margin-top: 20px;

	@for $i from 0 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}

	.login-content-password {
		display: inline-block;
		width: 20px;
		cursor: pointer;

		&:hover {
			color: #909399;
		}
	}

	.login-content-code {
		display: flex;
		align-items: center;
		justify-content: space-around;

		.login-content-code-img {
			width: 100%;
			height: 40px;
			line-height: 40px;
			background-color: #ffffff;
			border: 1px solid rgb(220, 223, 230);
			cursor: pointer;
			transition: all ease 0.2s;
			border-radius: 4px;
			user-select: none;

			&:hover {
				border-color: #c0c4cc;
				transition: all ease 0.2s;
			}
		}
	}

	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 300;
		margin-top: 15px;
	}

	.login-msg {
		color: var(--el-text-color-placeholder);
	}
}
</style>
